<?php
/**
 * Created by PhpStorm.
 * User: BlueIdeaLirui
 * Date: 2019/09/03
 * Time: 14:58
 */

namespace business\datacenter\services;

use business\datacenter\repositories\LandRepository;
use business\elasticsearch\repositories\LandRepository as EsLandRepository;
use common\utils\DateTimeUtils;

class LandCronService
{
    /**
     * 处理拿地数据同步到es
     * @param int $type
     * @throws \yii\db\Exception
     */
    public function processLandDataRsyncToEs($type = 1, $isCreateIndex = 1, $page = 0)
    {
        set_time_limit(0);
        $landRepository = new LandRepository();
        $funcs          = ['LandTake', 'LandConstruction', 'LandProject'];
        $condition      = ['is_deleted' => 0];
        $microSecond    = 50 * 1000;
        $num            = 1;
        $size           = 1000;

        if (!empty($page)) {
            $num = $page;
        }

        $lastTimeFunc = 'get' . $funcs[$type-1] . 'One';

        $pointOfTime    = $landRepository->{$lastTimeFunc}($condition,
            'updated_time', ['updated_time' => SORT_ASC])['updated_time'];

        $landDataRsyncToEsCronRecord = $landRepository->getLandDataRsyncToEsCronRecord(['type_id' => $type]);

        if (!empty($landDataRsyncToEsCronRecord)) {
            $starTime = $landDataRsyncToEsCronRecord['end_time'];
        } else {
            if ($isCreateIndex == 1) {
                // 初始化创建索引
                echo '正在创建索引...' . PHP_EOL;
                $createIndexFunc = 'create' . $funcs[$type-1] . 'Index';
                (new EsLandRepository())->{$createIndexFunc}();
                echo '索引创建成功...' . PHP_EOL;
            }
            $starTime = $pointOfTime;
        }

        $endTime = date('Y-m-d H:i:s', DateTimeUtils::time());

        $landRepository->storeLandDataRsyncToEsCronRecord(
            ['type_id' => $type, 'start_time' => $starTime, 'end_time' => $endTime]);

        echo '正在同步数据...' . PHP_EOL;

        do {
            $listFunc = 'get' . $funcs[$type-1] . 'List';
            $list = call_user_func_array([$this, $listFunc], [$starTime, $endTime, $num, $size]);
            if (!empty($list)) {
                $rsyncFunc = 'rsync' . $funcs[$type-1] . 'ToEs';
                call_user_func_array([$this, $rsyncFunc], [$list, $starTime, $endTime, $num, $size]);
                $num++;
                usleep($microSecond);
            } else {
                $num = 1;
                break;
            }
        } while (true);
    }

    /**
     * 返回大数据拓客--拿地数据列表
     * @param $starTime
     * @param $endTime
     * @param $page
     * @param $size
     * @return array
     * @throws \yii\db\Exception
     */
    public function getLandTakeList($starTime, $endTime, $page, $size)
    {
        $landRepository = new LandRepository();
        $offset = ($page - 1) * $size;
        echo implode('|', [$page, $offset, $starTime, $endTime]) . PHP_EOL;
        return $landRepository->getLandTakeList(['is_deleted' => 0], $starTime, $endTime, '*', $offset, $size);
    }

    /**
     * 返回大数据拓客--开工数据列表
     * @param $starTime
     * @param $endTime
     * @param $page
     * @param $size
     * @return array
     * @throws \yii\db\Exception
     */
    public function getLandConstructionList($starTime, $endTime, $page, $size)
    {
        $landRepository = new LandRepository();
        $offset = ($page - 1) * $size;
        echo implode('|', [$page, $offset, $starTime, $endTime]) . PHP_EOL;
        return $landRepository->getLandConstructionList(['is_deleted' => 0], $starTime, $endTime, '*', $offset, $size);
    }

    /**
     * 大数据拓客--项目数据表
     * @param $starTime
     * @param $endTime
     * @param $page
     * @param $size
     */
    public function getLandProjectList($starTime, $endTime, $page, $size)
    {
        $landRepository = new LandRepository();
        $offset = ($page - 1) * $size;
        echo implode('|', [$page, $offset, $starTime, $endTime]) . PHP_EOL;
        return $landRepository->getLandProjectList(['is_deleted' => 0], $starTime, $endTime, '*', $offset, $size);
    }

    /**
     * 拿地数据同步到es中
     * @param array $data
     * @return array
     */
    public function rsyncLandTakeToEs(
        $data = [],
        $starTime = '',
        $endTime = '',
        $page = 0,
        $size = 0
    ) {
        if (!empty($data)) {
            foreach ($data as $value) {
                echo $result = var_export($value, true) . PHP_EOL;
                try {
                    (new EsLandRepository())->saveLandTakeRecord($value, $value['uid']);
                } catch (\Exception $ex) {
                    (new LandRepository())->storeLandDataRsyncToEsErrorLog([
                        'type_id'       => 1,
                        'error_message' => var_export(['page' => $page, 'size' => $size, 'info' => $result], true),
                        'start_time'    => $starTime,
                        'end_time'      => $endTime,
                        'created_time'  => DateTimeUtils::now()
                    ]);
                }
            }
        }

        return [];
    }

    /**
     * 开工数据同步到es中
     * @param array $data
     * @return array
     */
    public function rsyncLandConstructionToEs(
        $data = [],
        $starTime = '',
        $endTime = '',
        $page = 0,
        $size = 0
    ) {
        if (!empty($data)) {
            $pattern = '/(\d+\.?\d?)/';
            foreach ($data as & $value) {
                if(preg_match_all($pattern, $value['contract_price'], $match)){
                    // 去掉万元字符
                    $value['contract_price'] = $match[0][0];
                } else {
                    $value['contract_price'] = '';
                }

                $value['issuing_time'] == '0000-00-00 00:00:00' && $value['issuing_time'] = null;

                echo $result = var_export($value, true) . PHP_EOL;

                try {
                    (new EsLandRepository())->saveLandConstructionRecord($value, $value['uid']);
                } catch (\Exception $ex) {
                    (new LandRepository())->storeLandDataRsyncToEsErrorLog([
                        'type_id'       => 2,
                        'error_message' => var_export(['page' => $page, 'size' => $size, 'info' => $result], true),
                        'start_time'    => $starTime,
                        'end_time'      => $endTime,
                        'created_time'  => DateTimeUtils::now()
                    ]);
                }
            }
        }

        return [];
    }

    /**
     * 项目数据同步到es中
     * @param array $data
     * @return array
     */
    public function rsyncLandProjectToEs(
        $data = [],
        $starTime = '',
        $endTime = '',
        $page = 0,
        $size = 0
    ) {
        if (!empty($data)) {
            foreach ($data as $value) {
                $offset = 15;

                $tmpValue1 = $tmpValue2 = $value;
                $totalPrice = 0;

                if (!empty($value['price'])) {
                    $totalPrice = $value['area'] * $value['price'];
                }

                $tmp = array_merge(
                    array_splice($tmpValue1,0, $offset),
                    ['total_price' => $totalPrice],
                    array_splice($tmpValue2, $offset)
                );

                $tmp['opening_time'] == '0000-00-00 00:00:00' && $tmp['opening_time'] = null;

                echo $result = var_export($tmp, true) . PHP_EOL;

                try {
                    (new EsLandRepository())->saveLandProjectRecord($tmp, $value['uid']);
                } catch (\Exception $ex) {
                    (new LandRepository())->storeLandDataRsyncToEsErrorLog([
                        'type_id'       => 3,
                        'error_message' => var_export(['page' => $page, 'size' => $size, 'info' => $result], true),
                        'start_time'    => $starTime,
                        'end_time'      => $endTime,
                        'created_time'  => DateTimeUtils::now()
                    ]);
                }
            }
        }

        return [];
    }
}
